package com.wichell.framework.wechat.util;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.wichell.framework.util.JacksonUtil;
import com.wichell.framework.wechat.bo.response.WechatQrcodeTicket;
import com.wichell.framework.wechat.contants.WechatContants;
import com.wichell.framework.wechat.exception.WechatRequestException;

/**   
 * @ClassName:  QrcodeUtils   
 * @Description:二维码工具类
 * @author: Isaac
 * @date:   2018年2月13日 下午3:17:03   
 *     
 * @Copyright: 2018 www.wichell.com Inc. All rights reserved.
 */
public class QrcodeUtils {

	/**   
	 * @Title: createQrcode   
	 * @Description: 生成带参数的二维码
	 * @param: @param isTemp 是否临时二维码
	 * @param: @param token accessToken
	 * @param: @param expires 二维码有效时间，以秒为单位。 最大不超过2592000（即30天），此字段如果不填，则默认有效期为30秒。
	 * @param: @param sceneId 场景值ID，临时二维码时为32位非0整型，永久二维码时最大值为100000（目前参数只支持1--100000）
	 * @param: @param sceneStr 场景值ID（字符串形式的ID），字符串类型，长度限制为1到64
	 * @param: @return
	 * @param: @throws WechatRequestException      
	 * @return: WechatAccessToken      
	 * @throws   
	 */
	public static WechatQrcodeTicket createQrcode(Boolean isTemp, String token, Integer expires, Integer sceneId,
			String sceneStr) throws WechatRequestException {
		// {"expire_seconds": 604800, "action_name": "QR_STR_SCENE", "action_info":
		// {"scene": {"scene_str": "test","scene_id": 123}}}
		Map<String, Object> map = packParam(isTemp, expires, sceneId, sceneStr);

		String createQrcodeUrl = MessageFormat.format(WechatContants.CREATEQRCODETICKETURL, token);
		try {
			return WechatUtils.request(createQrcodeUrl, JacksonUtil.obj2Json(map));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			throw new WechatRequestException("参数转换异常:" + e.getMessage());
		}
	}

	private static Map<String, Object> packParam(Boolean isTemp, Integer expires, Integer sceneId, String sceneStr)
			throws WechatRequestException {
		if (sceneId == null && StringUtils.isBlank(sceneStr)) {
			throw new WechatRequestException("参数不能全为空");
		}

		if (isTemp) {
			expires = (expires == null || expires <= 0) ? 30 : expires;
			if (expires > 2592000) {
				throw new WechatRequestException("二维码有效时间最大不超过2592000（即30天）");
			}
		}

		Map<String, Object> subMap = new HashMap<String, Object>(2);
		if (sceneId != null && (sceneId == 0 || sceneId > 100000)) {
			throw new WechatRequestException("sceneId必须为32位非0整型");
		} else {
			subMap.put("scene_id", sceneId);
		}
		if (StringUtils.isNotBlank(sceneStr) && sceneStr.length() > 64) {
			throw new WechatRequestException("sceneStr必须长度限制为1到64");
		} else {
			subMap.put("scene_str", sceneStr);
		}
		Map<String, Object> map = new HashMap<String, Object>(2);
		map.put("expire_seconds", expires);
		map.put("action_name", isTemp ? "QR_STR_SCENE" : "QR_LIMIT_STR_SCENE");
		map.put("action_info", subMap);

		return map;
	}

}
